import { login, userInfo, getUserDetailById } from '@/api/user'
import { Message } from 'element-ui'
import { setToken, getToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      token: getToken() || null,
      userinfo: {}
    }
  },
  mutations: {
    getToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    getUserinfo(state, Userinfo) {
      state.userinfo = Userinfo
    }
  },
  actions: {
    async login(context, loginForm) {
      try {
        const res = await login(loginForm)
        Message.success(res.message)
        console.log(res)
        context.commit('getToken', res.data)
      } catch (error) {
        Message.warning(error)
      }
    },
    async getuserInfo(context) {
      try {
        const res = await userInfo()
        const obj = await getUserDetailById(res.data.userId)
        const newRes = { ...res.data, ...obj.data }
        context.commit('getUserinfo', newRes)
      } catch (error) {
        console.dir(error)
        Message.warning(error)
      }
    },
    // 清空token
    removeUser(context) {
      context.commit('getToken', '')
      context.commit('getUserinfo', {})
    }
  }
}
